﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Ipmce.RemoteVoting.Common.Tools.CardReader.ImageParsing
{
	class FacialRecordData : IElement
	{
		public FacialInformation FacialInformation { get; set; }
		public List<FeaturePoint> FeaturePoints { get; set; }
		public ImageInformation ImageInformation { get; set; }
		public byte[] ImageData { get; set; }

		public int Parse(byte[] data, int offset)
		{
			int newOffset = offset;
			newOffset = FacialInformation.Parse(data, newOffset);
			for (var i = 0; i < FacialInformation.NumberOfFeaturePoints; i++)
			{
				var item = new FeaturePoint();
				newOffset = item.Parse(data, newOffset);
				FeaturePoints.Add(item);
			}
			newOffset = ImageInformation.Parse(data, newOffset);

			ImageData = new byte[FacialInformation.FacialRecordDataLength - (newOffset - offset)];
			offset = newOffset;
			Array.Copy(data, offset, ImageData, 0, ImageData.Length);
			offset += ImageData.Length;

			return offset;            
		}

		public int Write(byte[] data, int offset)
		{
			offset = FacialInformation.Write(data, offset);
			offset = FeaturePoints.Aggregate(offset, (current, item) => item.Write(data, current));
			offset = ImageInformation.Write(data, offset);
			Array.Copy(ImageData, 0, data, offset, ImageData.Length);

			return offset;
		}

		public int GetSize()
		{
			return FacialInformation.GetSize() +
			       FeaturePoints.Sum(p => p.GetSize()) +
			       ImageInformation.GetSize() + 
			       ImageData.Length;
		}

		public FacialRecordData()
		{
			FacialInformation = new FacialInformation();
			FeaturePoints = new List<FeaturePoint>();
			ImageInformation = new ImageInformation();
		}

		public FacialRecordData(EnumFaceImageType faceImageType, ImageType imageDataType, int width, int height, byte[] imageData)
		{
			ImageData = imageData;
			ImageInformation = new ImageInformation(faceImageType, imageDataType, width, height);
			FeaturePoints = new List<FeaturePoint>();
			FacialInformation = new FacialInformation(this);
		}
	}
}